import Vue from 'vue'
import Vuex from 'vuex'
import bg5 from '@/assets/bg5.jpg'
import bg2 from '@/assets/bg2.jpg'
import bg3 from '@/assets/bg3.jpg'

Vue.use(Vuex)


const kimData = JSON.parse(localStorage.getItem('kim-data'))||{}||{ //本地存储的数据
    '10000':{
        chatlog:{
            'friend1001':[
                {
                    avatar: "http://res.itsub.cn/avatar/8.jpg",
                    content: "想飞上天和太阳肩并肩想飞上天和太阳肩并肩想飞上天和太阳肩并肩想飞上天和太阳肩并肩想飞上天和太阳肩并肩想飞上天和太阳肩并肩想飞上天和太阳肩并肩想飞上天和太阳肩并肩",
                    id: "10000",
                    mine: true,
                    timestamp: 1621300749049,
                    type: "friend",
                    name: "君莫笑",
                },
                {
                    avatar: "http://res.itsub.cn/avatar/1.jpg",
                    content: "狂沙百战穿金甲，不破楼兰终不还狂沙百战穿金甲，不破楼兰终不还狂沙百战穿金甲，不破楼兰终不还狂沙百战穿金甲，不破楼兰终不还狂沙百战穿金甲，不破楼兰终不还狂沙百战穿金甲，不破楼兰终不还",
                    id: "1001",
                    mine: false,
                    timestamp: 1621300748049,
                    type: "friend",
                    name: "狂沙百战",
                },
                {
                    system:true,
                    type:'friend',  //用于定位聊天
                    id: "1001",     //用于定位聊天
                    content: "这是一个系统消息",
                },

            ],
            /*'group101':[
                {
                    avatar: "",
                    content: "",
                    id: "10000",
                    mine: true,
                    timestamp: 1621300748049,
                    type: "group",
                    name: "好友名称",
                }
            ],*/
        },
    }
};
console.log('kimData',kimData)
function accountScope(){
    let mine_id = store.state.mine.id;
    let data = store.state.data;
    if (data[mine_id]) {
        data[mine_id] = {chatlog:{}};
    }
    return data[mine_id];
}

const users=[
    {
        name: "狂沙百战",
        id: "1001",
        avatar: "http://res.itsub.cn/avatar/1.jpg",
        sign: "飘零雪域凋残月，万丈剑芒映虚空",
        state: 1,
    },
    {
        name: "北悸安凉",
        id: "1002",
        avatar: "http://res.itsub.cn/avatar/2.jpg",
        sign: "黑夜之下，光明即将来临",
        state: 0
    },
    {
        name: "安澜",
        id: "1003",
        type:'friend',
        avatar: "http://res.itsub.cn/avatar/3.jpg",
        sign: "仙之巅，傲世间，有我安澜便有天！",
        state: 1,
    },
    {
        name: "俞陀",
        id: "1004",
        type:'friend',
        avatar: "http://res.itsub.cn/avatar/4.jpg",
        sign: "安澜挺住，我来救你",
        state: 1,
    },
];
function findUserById(userid) {
    console.log('find:'+userid)
    for (let u of users) {
        if (u.id == userid) {
            return u;
        }
    }
    return null;
}

function shake(store) {
    store.state.kimInstance.shake();
}
//上传图片，返回图片地址： url_callback(图片地址);
function _uploadImageHandler(file, url_callback) {
    let kim = store.state.kimInstance;
    let api = store.state.config.uploadImageApi;
    //上传图片
    let formData = new FormData();
    formData.append('file', file);
    //合并data到formData
    for (let key in api.data) {
        formData.append(key, api.data[key]);
    }
    kim.$axios.post(api.url, formData, {
        headers: { 'Content-Type': 'multipart/form-data',...api.headers }
    }).then(res=>{
        console.log(res)
        if (res.data.code==200){
            url_callback(res.data.url);
        }

    })
}

function chooseImage(store) {

    //选择图片
    let input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';
    input.onchange = function (e) {
        let file = e.target.files[0];
        /*let reader = new FileReader();
        reader.onload = function (e) {
            let base64 = e.target.result;
            store.state.chatboxInstance.imageLoaded(base64);
        }
        reader.readAsDataURL(file);*/

        store.state.config.uploadImageHandler(file, store.state.chatboxInstance.imageLoaded);

    }
    input.click();
}

const store = new Vuex.Store({
    state: {
        kimInstance:null, //kim实例
        chatboxInstance:null, //聊天窗口实例

        config:{ //配置信息
            //获取群成员列表，默认传递id参数是群聊id
            members:{
                url:'http://res.itsub.cn/json/kim.members.json',
                type:'get',
                data:{}
            },
            //聊天记录最大条数
            chatMsgMaxCount: 100,
            editorToolbar: [
                { type: "face", icon: '<span class="iconfont">&#xe696;</span>' , click: () => { console.log("face") }},
                { type: "img", icon: '<span class="iconfont">&#xe6a1;</span>' , click: () => { chooseImage(store) }},
                { type: "file", icon: '<span class="iconfont">&#xe683;</span>', click: () => { console.log("file") } },
                { type: "code", icon: '<span class="iconfont">&#xe65d;</span>', click: () => { console.log("code") } },
                { type: "shake", icon: '<span class="iconfont">&#xe68c;</span>', click: () => { shake(store) } },
            ],
            toolbar:[
                {text:'搜索',icon:'iconfont icon-search',click:function(){ console.log('搜索') }},
                {text:'消息盒子',icon:'iconfont icon-notification',click:function(){ console.log('消息盒子') }},
                {text:'发现',icon:'iconfont icon-add-circle',click:function(){ console.log('发现') }},
                {text:'皮肤',icon:'iconfont icon-layout',click:function(){ console.log('皮肤') }},
                {text:'关于',icon:'iconfont icon-prompt',click:function(){ console.log('关于') }},
            ],
            uploadImageApi:{
                url:'',
                data:{},
                headers:{}
            },
            uploadImageHandler:_uploadImageHandler,
        },
        count: 0,
        //skinImg:require('../skin/bg5.jpg'),
        skinList:[bg2,bg3,bg5],
        skinImg:bg5,
        chatboxShow:false,
        mine: {
            name: "KIM",
            id: "0",
            sign: "美好，如期而至",
            avatar: "http://res.itsub.cn/avatar/8.jpg",
            state:1, //在线状态，0离线或隐身，1在线
        },
        friends: [
           /* {
                groupname: "知名人物",
                open:true, //分组是否展开
                id: 1,//分组ID
                list: [
                    users[0],
                    users[1],
                ]
            },
            {
                groupname: "网络名人",
                open:true,
                id: 2,
                list: [
                    users[2],
                    users[3],
                ]
            }*/
        ],
        groups: [

        ],
        chats:[

        ],
        chating:[

        ],
        data:kimData,
    },
    mutations: {
        init(state,data){
            if (data.mine) state.mine=data.mine;
            if (data.friends)state.friends=data.friends;
            if (data.groups)state.groups=data.groups;
        },
        config(state, opts) {
            Object.assign(state.config, opts);
            console.log(state.config)
        },
        addChat (state,chat) {
            let user = null; //聊天目标
            for (let u of state.chats) {
                if (u.id == chat.id) {
                    user = u;
                }
            }
            if (!user) {
                state.chats.push(chat);
            }
        },
        updateUser(state, user) {
            console.log(user)
            let a = findUserById(user.id);
            console.log(a)
            //Object.assign(a, user);
            a.state=0;
        },
        addFriend(state, friend) {
            let r = state.friends.find(fg => fg.id == friend.gid);
            if (r) {
                //store.commit('removeFriend', friend.id);
                let f = r.list.find(fr => fr.id == friend.id);
                if (!f) {
                    r.list.push(friend);
                }else{
                    Object.assign(f, friend);
                }
            }
        },
        removeFriend(state, userid) {
            let r = store.findFriendIndex(userid);
            if (r) {
                state.friends[r.m].list.splice(r.n, 1);
            }
        },
        addMessage(state, data) {
            //data{ type,id, fromid,name,avatar,content,mine,timestamp }
            //type和id两个属性表示和谁的聊天，例如'friend100'，例如'group100'
            let target = data.type+''+data.id;
            let d = state.data;
            let a = d[state.mine.id];
            if (!a){
                a = d[state.mine.id] = {chatlog:{}};
            }
            let c = a.chatlog[target];
            if (!c) {
                c = a.chatlog[target] = [];
            }
            c.push(data);
            //保留最近N条聊天记录
            while (c.length > state.config.chatMsgMaxCount) {
                c.shift();
            }
            console.log('记录数：'+c.length)
            localStorage.setItem('kim-data', JSON.stringify(state.data));

            state.chatboxInstance && state.chatboxInstance.scrollToBottom(data.type, data.id);
        }
    },
    actions:{

    }
})

store.findFriendIndex=(id)=>{
    for (let m in store.state.friends) {
        let fg = store.state.friends[m];
        for (let n in fg.list) {
            let fr = fg.list[n];
            if (fr.id == id) {
                return {m:m,n:n}
            }
        }
    }
}
/* 根据id获取好友 */
store.getFriend=(fid)=>{
    return store.getFriendDict()[fid];
}
/* 获取好友字典（k:id，v:friend） */
store.getFriendDict=()=>{
    let map = {};
    for (let m in store.state.friends) {
        let fg = store.state.friends[m];
        for (let n in fg.list) {
            let fr = fg.list[n];
            fr.gid=fg.id;
            map[fr.id]=fr;
        }
    }
    return map;
}

export default store
